package com.ge.pp;

import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;
import java.util.Vector;


public class WindowLevelFilter extends ImageFilter {
	FilterAttribute window;
	FilterAttribute level;
	
	public WindowLevelFilter(PicturePane p, float windowVal, float levelVal) {
		super(p);
		name = "Window/Level Filter";
		window= new FilterAttribute("window", 1, 255, windowVal);
		level = new FilterAttribute("level", 0, 255, levelVal);
		attributes = new Vector<FilterAttribute>();
		attributes.add(window);
		attributes.add(level);
	}
	
	public BufferedImage filter(BufferedImage img) throws Exception {
		try
		{
		BufferedImage newImg = new BufferedImage(img.getWidth(), img.getHeight(), img.getType());
		Raster inRaster = img.getRaster();		
		WritableRaster r = newImg.getRaster();
		
		float [] f = new float[3];
		
		float l = level.val;
		float w = window.val;
		float pixel_step = 255.0f/w;
		
		for(int x=0; x<r.getWidth(); x++) {
			for (int y=0; y<r.getHeight(); y++) {
				inRaster.getPixel(x, y, f);
				for(int i=0; i<3; i++) {
					if(f[i]<l-w/2) 
						f[i] = 0;
					else if(f[i]>l+w/2) 
						f[i] = 255;
					else {
						f[i] = (f[i] - (l - (w/2)))*pixel_step;							
					}						
				}
				r.setPixel(x,y, f);
			}
		}			

		return newImg;
		}
		catch(Exception e)
		{
			throw e;
		}
	}
}